
//栈
function Stack() {
    //栈的节点
    var Node = function (key) {
        this.key = key;
        //this.next = null;
        this.pre = null;
    }

    //栈顶
    var top = null;

    //入栈
    this.push = function (key) {
        var newNode = new Node(key);
        console.log(key + " 入栈");
        if (top === null) {
            top = newNode;
        }
        else {
            var temp = top;
            top = newNode;
            top.pre = temp;
            temp = null;
        }
        return top;
    }

    //出栈
    this.pop = function () {
        if (top === null) {
            return null;
        } else {
            console.log(top.key + " 出栈");

            var temp = top;
            top = top.pre;
            return temp;
        }
    }

    //遍历
    this.print = function () {
        var temp = top;
        var str = "";
        while (top) {
            str += " " + top.key;
            top = top.pre;
        }
        console.log(str);
        top = temp;
        temp = null;
    }

    this.getLength = function () {
        var len = 0;
        var temp = top;
        while (top) {
            len++;
            top = top.pre;
        }
        top = temp;
        temp = null;
        return len;
    }

}

// node stack/stack.js
var nodes = [89, 34, 98, 12, 88];
var stack = new Stack();
var len = nodes.length;
for (var i = 0; i < len; i++) {
    stack.push(nodes[i]);
}
stack.print();
stack.pop();
stack.pop();
stack.pop();
stack.print();
stack.push(1);
stack.push(2);
stack.push(3);
console.log("栈的长度：" + stack.getLength());
stack.print();
stack.push(66);
stack.push(77);
stack.pop();
stack.print();   
